﻿using DimensionData.Data2;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace CPPEI.PM.Shell.Views
{
    /// <summary>
    /// Interaction logic for WorkSheetView.xaml
    /// </summary>
    public partial class WorkSheetView : UserControl
    {
        private WorkSheet _currentWorkSheet;

        public Guid WorkSheetId { get; private set; }

        public WorkSheetView()
        {
            InitializeComponent();
        }

        private void BindToDataGrid(WorkSheet workSheet)
        {
            this._ctlDataGrid.ItemsSource = null;

            BuildDataSchema(this._ctlDataGrid, workSheet);

            this._ctlDataGrid.ItemsSource = _currentWorkSheet.RowCollection;
        }

        private string GetBindingPath(int depth)
        {
            StringBuilder builder = new StringBuilder();
            for (int index = 0; index < depth; index++)
            {
                builder.Append("Parent.");
            }
            builder.Append("Caption");
            return builder.ToString();
        }

        private void _ctlBtnCreateWorkStage_Click_1(object sender, RoutedEventArgs e)
        {
            WorkStage newWorkStage = new WorkStage();
            newWorkStage.Id = Guid.NewGuid();
            newWorkStage.Caption = "新阶段";
            WorkStageRef newWorkStageRef = new WorkStageRef();
            newWorkStageRef.Id = newWorkStage.Id;
            newWorkStageRef.Caption = newWorkStage.Caption;
            newWorkStageRef.Level = 0;
            _currentWorkSheet.WorkStageCollection.Add(newWorkStageRef);

            BindToDataGrid(_currentWorkSheet);
        }

        private void _ctlBtnWorkStageFilter_Click_1(object sender, RoutedEventArgs e)
        {
            Dialogs.WorkStageFilterDlg dlg = new Dialogs.WorkStageFilterDlg(_currentWorkSheet);
            if (dlg.ShowDialog() == true)
            {
                BindToDataGrid(_currentWorkSheet);
            }
        }

        public void LoadWorkSheet(Guid workSheetId)
        {
            WorkSheetId = workSheetId;

            PMServiceRef.PMWebServiceSoapClient client = new PMServiceRef.PMWebServiceSoapClient();
            // 获取服务器上的工作表信息
            PMServiceRef.WorkSheet workSheet = client.GetWorkSheet(UIContext.Instance.ProjectId, workSheetId);

            _currentWorkSheet = new WorkSheet();
            _currentWorkSheet.Id = workSheet.Id;
            _currentWorkSheet.Caption = workSheet.Caption;
            _currentWorkSheet.Changeset = 1;

            _currentWorkSheet.DDoc = new DimensionData.Data2.DDoc();
            _currentWorkSheet.DDoc.YTree = this.LoadWorkItem2Tree(_currentWorkSheet);
            _currentWorkSheet.DDoc.XTree = this.LoadWorkStage2Tree(_currentWorkSheet);

            _currentWorkSheet.BuildData();

            AttachData(_currentWorkSheet);

            BindToDataGrid(_currentWorkSheet);
        }

        private static void BuildDataSchema(DataGrid dataGrid, WorkSheet workSheet)
        {
            dataGrid.Columns.Clear();

            // 创建工作项的列
            for (int index = 0; index < workSheet.DDoc.YTree.Table.Tables.Count; index++)
            {
                DTable dTable = workSheet.DDoc.YTree.Table.Tables[index];
                DataGridTextColumn columnCaption = new DataGridTextColumn();
                columnCaption.Header = dTable.Name;
                Binding binding = new Binding(string.Format("[{0},]", index));
                binding.Mode = BindingMode.TwoWay;
                binding.UpdateSourceTrigger = UpdateSourceTrigger.LostFocus;
                columnCaption.Binding = binding;
                dataGrid.Columns.Add(columnCaption);
            }

            List<DRow> xDRows = workSheet.DDoc.XTree.Complanate2();

            for (int index = 0; index < xDRows.Count; index++)
            {
                DRow xDRow = xDRows[index];
                DItem xDItem = xDRow.Items.Last();

                DataGridTextColumn column = new DataGridTextColumn();
                column.Header = xDItem.Name;
                Binding binding = new Binding(string.Format("[0,{0}]", xDRow.DPath));
                binding.Mode = BindingMode.TwoWay;
                binding.UpdateSourceTrigger = UpdateSourceTrigger.LostFocus;
                column.Binding = binding;
                dataGrid.Columns.Add(column);
            }
        }

        private static void AttachData(WorkSheet workSheet)
        {
            PMServiceRef.PMWebServiceSoapClient client = new PMServiceRef.PMWebServiceSoapClient();

            PMServiceRef.WorkSheetCell[] cells = client.GetWorkSheetCells(UIContext.Instance.Account,
                UIContext.Instance.Project.Id,
                workSheet.Id);
            bool isFilled = false;
            for (int index = 0; index < cells.Length; index++)
            {
                PMServiceRef.WorkSheetCell cellRef = cells[index];
                isFilled = false;
                for (int iRow = 0; iRow < workSheet.RowCollection.Count; iRow++)
                {
                    WorkSheetRow row = workSheet.RowCollection[iRow];
                    for (int iCell = 0; iCell < row.CellCollection.Count; iCell++)
                    {
                        WorkSheetCell cell = row.CellCollection[iCell];

                        if (string.Equals(cellRef.Path, cell.Path) && cell.State == BD_State.None)
                        {
                            cell.Value = cellRef.Value;
                            isFilled = true;
                            break;
                        }
                    }

                    if (isFilled)
                    {
                        break;
                    }
                }
            }
        }

        /// <summary>
        /// 创建已新工作项
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnCtlBtnCreateWorkItemClick(object sender, RoutedEventArgs e)
        {
            WorkSheetRow selRow = _ctlDataGrid.SelectedItem as WorkSheetRow;
            if (selRow == null)
            {
                return;
            }

            PMServiceRef.PMWebServiceSoapClient client = new PMServiceRef.PMWebServiceSoapClient();

            // 创建WorkItem
            WorkItem newWorkItem = new WorkItem();
            newWorkItem.Id = Guid.NewGuid();
            newWorkItem.Code = "c" + DateTime.Now.Ticks.ToString();
            newWorkItem.Caption = "新项目";
            PMServiceRef.WorkItemCategory workItemCategory = client.GetWorkItemCategoryByCode(UIContext.Instance.Project.Id,
                _currentWorkSheet.DDoc.YTree.Table.Tables.Last().Code);
            newWorkItem.CategoryCode = workItemCategory.Code;
            newWorkItem.WorkItemCategoryId = workItemCategory.Id;
            newWorkItem.State = BD_State.Added;
            UIContext.Instance.Project.WorkItemList.Add(newWorkItem);

            WorkItemRef newWorkItemRef = new WorkItemRef();
            newWorkItemRef.Id = newWorkItem.Id;
            newWorkItemRef.WorkItemCategoryId = workItemCategory.Id;
            newWorkItemRef.Caption = newWorkItem.Caption;
            newWorkItemRef.CategoryCode = newWorkItem.CategoryCode;
            newWorkItemRef.State = BD_State.Added;
            _currentWorkSheet.WorkItemCollection.Add(newWorkItemRef);

            // 找到YDTree上的节点
            DTreeNode dTreeNode = _currentWorkSheet.DDoc.YTree.GetNode(selRow.YDRow.DPath);

            DTreeNode newDTreeNode = new DTreeNode();
            newDTreeNode.Level = dTreeNode.Level;
            newDTreeNode.Code = newWorkItem.Code;
            newDTreeNode.Name = newWorkItem.Caption;
            if (dTreeNode.ParentNode != null)
            {
                dTreeNode.ParentNode.InsertBefore(dTreeNode, newDTreeNode);
                newDTreeNode.Tree = dTreeNode.Tree;
                newDTreeNode.ParentNode = dTreeNode.ParentNode;

                DRow newDRow = newDTreeNode.GetDRow();
                _currentWorkSheet.InsertRow(dTreeNode.GetDRow(), newDRow);
            }
            else
            {
                dTreeNode.Tree.InsertBefore(dTreeNode, newDTreeNode);
                newDTreeNode.Tree = dTreeNode.Tree;
                newDTreeNode.ParentNode = dTreeNode.ParentNode;

                DRow newDRow = newDTreeNode.GetDRow();
                _currentWorkSheet.InsertRow(dTreeNode.GetDRow(), newDRow);
            }

            this._ctlDataGrid.ItemsSource = null;
            this._ctlDataGrid.ItemsSource = _currentWorkSheet.RowCollection;
        }

        private void _ctlBtnSave_Click_1(object sender, RoutedEventArgs e)
        {
            for (int index = 0; index < UIContext.Instance.Project.WorkItemList.Count; index++)
            {
                WorkItem item = UIContext.Instance.Project.WorkItemList[index];
                if (item.State == BD_State.Added)
                {
                    // 创建
                    PMServiceRef.WorkItem newWorkItem = new PMServiceRef.WorkItem();
                    newWorkItem.Id = item.Id;
                    newWorkItem.Code = item.Code;
                    newWorkItem.Caption = item.Caption;
                    new PMServiceRef.PMWebServiceSoapClient().CreateWorkItem(UIContext.Instance.Account, UIContext.Instance.Project.Id, item.WorkItemCategoryId, newWorkItem);

                    item.State = BD_State.None;
                }
            }

            // 同步工作表结构
            for (int iWIRef = 0; iWIRef < this._currentWorkSheet.WorkItemCollection.Count; iWIRef++)
            {
                WorkItemRef item = _currentWorkSheet.WorkItemCollection[iWIRef];
                if (item.State != BD_State.None)
                {
                    new PMServiceRef.PMWebServiceSoapClient().RefWorkItem(UIContext.Instance.Account,
                        UIContext.Instance.Project.Id,
                        _currentWorkSheet.Id,
                        item.WorkItemCategoryId,
                        Guid.Empty,
                        item.Id,
                        true);
                    item.State = BD_State.None;
                }
            }

            // 保存工作表数据
            List<PMServiceRef.WorkSheetCell> updatedCellList = new List<PMServiceRef.WorkSheetCell>();
            for (int iRow = 0; iRow < this._currentWorkSheet.RowCollection.Count; iRow++)
            {
                WorkSheetRow row = this._currentWorkSheet.RowCollection[iRow];
                for (int iCell = 0; iCell < row.CellCollection.Count; iCell++)
                {
                    WorkSheetCell cell = row.CellCollection[iCell];
                    if (cell.State != BD_State.None)
                    {
                        PMServiceRef.WorkSheetCell updatedCell = new PMServiceRef.WorkSheetCell();
                        updatedCell.Path = cell.Path;
                        updatedCell.Value = cell.Value.ToString();
                        updatedCell.Text = string.Empty;
                        updatedCellList.Add(updatedCell);

                        cell.State = BD_State.None;
                    }
                }
            }
            if (updatedCellList.Count > 0)
            {
                new PMServiceRef.PMWebServiceSoapClient().UpdateWorkSheetCells(UIContext.Instance.Account,
                    UIContext.Instance.Project.Id,
                    this._currentWorkSheet.Id,
                    updatedCellList.ToArray());
            }
        }

        private void _ctlBtnSync_Click_1(object sender, RoutedEventArgs e)
        {
            // 将状态不等于None的都上传到服务器上
            Dialogs.SyncDlg dlg = new Dialogs.SyncDlg();
            dlg.ShowDialog();
        }

        private void _ctlDataGrid_BeginningEdit_1(object sender, DataGridBeginningEditEventArgs e)
        {
        }
    }
}
